题目:利用 XMLHttpRequest 手写 AJAX 实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| function getAjax (url) { return new Promise((resolve, reject) => { const xhr = new XMLHttpRequest(); xhr.open('GET', url, false); xhr.setRequestHeader("Content-Type", "application/json"); xhr.onreadystatechange = function () { if (xhr.readyState !== 4) return; if (xhr.status === 200 || xhr.status ===304) { resolve(xhr.responseText); } else { reject(new Error(xhr.responseText)); } }; xhr.send(); }); };
|
1 2
| getAjax('https://www.baidu.com');
|
结果: